package win_bridge

import (
	"github.com/capnspacehook/taskmaster"
	"github.com/pkg/errors"
	"github.com/rickb777/date/period"
	"os"
	"time"
)

var (
	TaskFolder = `\校园网工具`
	TaskPath   = TaskFolder + `\校园网WIFI自动认证`
)

type Tasker struct {
	service taskmaster.TaskService
}

func NewTasker() (*Tasker, error) {
	service, err := taskmaster.Connect()
	if err != nil {
		return nil, err
	}

	return &Tasker{service: service}, nil
}

func (t *Tasker) Release() {
	t.service.Disconnect()
}

func (t *Tasker) GetTask() (*taskmaster.RegisteredTask, error) {
	task, err := t.service.GetRegisteredTask(TaskPath)
	if err != nil {
		return nil, err
	}

	return &task, nil
}

func (t *Tasker) DeleteTask() error {
	err := t.service.DeleteTask(TaskPath)
	if err != nil {
		return err
	}

	return nil
}

func (t *Tasker) DeleteFolder() error {
	_, err := t.service.DeleteFolder(TaskFolder, true)
	return err
}

func (t *Tasker) CreateTask() error {
	xml := `
<QueryList>
  <Query Id="0" Path="Microsoft-Windows-WLAN-AutoConfig/Operational">
    <Select Path="Microsoft-Windows-WLAN-AutoConfig/Operational">
    *[System[(EventID=8001)]] and
    *[EventData[
                Data[@Name='SSID']='CFNMXX' or 
                Data[@Name='SSID']='YYJSWIFI-5G' or 
                Data[@Name='SSID']='YYJSWIFI-2.4G' 
	]]
    </Select>
  </Query>
</QueryList>
`

	exe, err := os.Executable()
	if err != nil {
		return errors.WithMessage(err, "获取可执行文件路径")
	}
	one, _ := period.NewOf(time.Second * 1)
	definition := t.service.NewTaskDefinition()
	definition.AddAction(
		taskmaster.ExecAction{
			Path: exe,
			Args: "auth",
		},
	)
	definition.AddTrigger(
		taskmaster.SessionStateChangeTrigger{
			Delay:       one,
			StateChange: taskmaster.TASK_SESSION_UNLOCK,
			TaskTrigger: taskmaster.TaskTrigger{Enabled: true},
		},
	)

	definition.AddTrigger(
		taskmaster.LogonTrigger{
			Delay:       one,
			TaskTrigger: taskmaster.TaskTrigger{Enabled: true},
		},
	)

	definition.AddTrigger(
		taskmaster.EventTrigger{
			Subscription: xml,
			Delay:        one,
			TaskTrigger:  taskmaster.TaskTrigger{Enabled: true},
		},
	)

	definition.Principal.RunLevel = taskmaster.TASK_RUNLEVEL_HIGHEST
	definition.Settings.StopIfGoingOnBatteries = true
	definition.Settings.DontStartOnBatteries = false
	definition.RegistrationInfo.Description = "当 进入桌面 or 连接至校园网WIFI 时启动程序进行认证"

	_, b, err := t.service.CreateTask(TaskPath,
		definition, true,
	)

	if !b || err != nil {
		return errors.WithMessage(err, "创建任务")
	}
	return nil
}
